package org.springframework.boot.netty.converter;

import org.springframework.beans.BeanUtils;
import org.springframework.boot.netty.exception.ConvertException;
import org.springframework.boot.netty.support.JsonUtil;
import org.springframework.context.annotation.Bean;

/**
 * Author: huoxingzhi
 * Date: 2020/12/10
 * Email: hxz_798561819@163.com
 */
public class JsonMessageConverter implements MessageConverter {

    public JsonMessageConverter() {

    }


    /**
     * string --> obj
     * @param source
     * @param target
     * @return
     */
    @Override
    public boolean fromSupport(Class<?> source, Class<?> target) {
        return String.class.isAssignableFrom(source);
    }

    /**
     * obj --> string
     * @param source
     * @param target
     * @return
     */
    @Override
    public boolean toSupport(Class<?> source, Class<?> target) {
        boolean supportSource = !BeanUtils.isSimpleValueType(source) || String.class.isAssignableFrom(source);
        return supportSource && String.class.isAssignableFrom(target);
    }

    @Override
    public <T> T fromMessage(Object jsonMessage, Class<T> clazz) throws ConvertException {

        return JsonUtil.string2Obj((String)jsonMessage, clazz);
    }

    @Override
    public Object toMessage(Class<?> clazz, Object object) {

        return JsonUtil.obj2String(object);
    }


}
